<template>
  <div class="customer-detail">
    <el-page-header @back="goBack" :title="customerId ? '客户详情' : '新增客户'">
      <template #content>
        <span class="page-header-content">
          {{ customerId ? customerInfo.name : '新增客户' }}
        </span>
      </template>
    </el-page-header>

    <div class="detail-content">
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form 
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
            class="detail-form"
          >
            <el-card class="form-card">
              <template #header>
                <div class="card-header">
                  <h3>基本信息</h3>
                  <div class="header-actions" v-if="!isEdit">
                    <el-button type="primary" @click="handleEdit">编辑</el-button>
                  </div>
                </div>
              </template>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="basicForm.name" :disabled="!isEdit" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户类型" prop="type">
                    <el-select v-model="basicForm.type" :disabled="!isEdit" style="width: 100%">
                      <el-option label="个人" value="personal" />
                      <el-option label="企业" value="enterprise" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="证件类型" prop="idType">
                    <el-select v-model="basicForm.idType" :disabled="!isEdit" style="width: 100%">
                      <el-option label="身份证" value="ID_CARD" />
                      <el-option label="护照" value="PASSPORT" />
                      <el-option label="营业执照" value="BUSINESS_LICENSE" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="证件号码" prop="idNumber">
                    <el-input v-model="basicForm.idNumber" :disabled="!isEdit" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="basicForm.phone" :disabled="!isEdit" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="basicForm.email" :disabled="!isEdit" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="联系地址" prop="address">
                <el-input v-model="basicForm.address" :disabled="!isEdit" />
              </el-form-item>

              <el-form-item v-if="isEdit">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="cancelEdit">取消</el-button>
              </el-form-item>
            </el-card>
          </el-form>
        </el-tab-pane>

        <!-- 贷款记录 -->
        <el-tab-pane label="贷款记录" name="loan">
          <el-card>
            <el-table :data="loanRecords" style="width: 100%">
              <el-table-column prop="loanNo" label="贷款编号" width="180" />
              <el-table-column prop="amount" label="贷款金额">
                <template #default="scope">
                  {{ formatMoney(scope.row.amount) }}
                </template>
              </el-table-column>
              <el-table-column prop="term" label="期限" width="100">
                <template #default="scope">
                  {{ scope.row.term }}个月
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getLoanStatusType(scope.row.status)">
                    {{ getLoanStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="applyTime" label="申请时间" width="180" />
              <el-table-column prop="approveTime" label="审批时间" width="180" />
            </el-table>
          </el-card>
        </el-tab-pane>

        <!-- 回访记录 -->
        <el-tab-pane label="回访记录" name="visit">
          <el-card>
            <template #header>
              <div class="card-header">
                <h3>回访记录</h3>
                <el-button type="primary" @click="handleAddVisit">添加回访</el-button>
              </div>
            </template>

            <el-timeline>
              <el-timeline-item
                v-for="(visit, index) in visitRecords"
                :key="index"
                :timestamp="visit.visitTime"
                :type="getVisitType(visit.method)"
              >
                <el-card class="timeline-card">
                  <template #header>
                    <div class="visit-header">
                      <span>回访方式：{{ getVisitMethodText(visit.method) }}</span>
                      <el-rate 
                        v-model="visit.feedback"
                        disabled
                        show-score
                        text-color="#ff9900"
                      />
                    </div>
                  </template>
                  <p>{{ visit.content }}</p>
                  <p class="visit-footer">
                    <span>回访人：{{ visit.visitor }}</span>
                    <span>下次回访：{{ visit.nextVisitTime }}</span>
                  </p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-tab-pane>

        <!-- 服务记录 -->
        <el-tab-pane label="服务记录" name="service">
          <el-card>
            <template #header>
              <div class="card-header">
                <h3>服务记录</h3>
                <el-button type="primary" @click="handleAddService">添加服务</el-button>
              </div>
            </template>

            <el-table :data="serviceRecords" style="width: 100%">
              <el-table-column prop="type" label="服务类型" width="120">
                <template #default="scope">
                  {{ getServiceTypeText(scope.row.type) }}
                </template>
              </el-table-column>
              <el-table-column prop="title" label="服务主题" width="200" />
              <el-table-column prop="content" label="服务内容" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getServiceStatusType(scope.row.status)">
                    {{ getServiceStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="180" />
              <el-table-column prop="handler" label="处理人" width="120" />
            </el-table>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 回访记录对话框 -->
    <el-dialog 
      v-model="visitDialogVisible" 
      title="添加回访记录"
      width="500px"
    >
      <el-form 
        :model="visitForm" 
        :rules="visitRules" 
        ref="visitFormRef"
        label-width="100px"
      >
        <el-form-item label="回访方式" prop="method">
          <el-select v-model="visitForm.method" placeholder="请选择回访方式" style="width: 100%">
            <el-option label="电话" value="phone" />
            <el-option label="上门" value="visit" />
            <el-option label="邮件" value="email" />
          </el-select>
        </el-form-item>
        <el-form-item label="回访内容" prop="content">
          <el-input
            type="textarea"
            v-model="visitForm.content"
            :rows="3"
            placeholder="请输入回访内容"
          />
        </el-form-item>
        <el-form-item label="客户反馈" prop="feedback">
          <el-rate 
            v-model="visitForm.feedback"
            :texts="['很差', '较差', '一般', '满意', '很满意']"
            show-text
          />
        </el-form-item>
        <el-form-item label="下次回访" prop="nextVisitTime">
          <el-date-picker
            v-model="visitForm.nextVisitTime"
            type="datetime"
            placeholder="请选择下次回访时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitVisit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务记录对话框 -->
    <el-dialog 
      v-model="serviceDialogVisible" 
      title="添加服务记录"
      width="500px"
    >
      <el-form 
        :model="serviceForm" 
        :rules="serviceRules" 
        ref="serviceFormRef"
        label-width="100px"
      >
        <el-form-item label="服务类型" prop="type">
          <el-select v-model="serviceForm.type" placeholder="请选择服务类型" style="width: 100%">
            <el-option label="咨询" value="consult" />
            <el-option label="投诉" value="complaint" />
            <el-option label="建议" value="suggestion" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务主题" prop="title">
          <el-input v-model="serviceForm.title" placeholder="请输入服务主题" />
        </el-form-item>
        <el-form-item label="服务内容" prop="content">
          <el-input
            type="textarea"
            v-model="serviceForm.content"
            :rows="3"
            placeholder="请输入服务内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitService">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { customerApi } from '@/api/customer'

export default {
  name: 'CustomerDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const customerId = route.params.id
    const loading = ref(false)

    // 基本信息表单
    const basicFormRef = ref(null)
    const isEdit = ref(false)
    const basicForm = reactive({
      name: '',
      type: 'personal',
      idType: 'ID_CARD',
      idNumber: '',
      phone: '',
      email: '',
      address: ''
    })

    const basicRules = {
      name: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择客户类型', trigger: 'change' }
      ],
      idType: [
        { required: true, message: '请选择证件类型', trigger: 'change' }
      ],
      idNumber: [
        { required: true, message: '请输入证件号码', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      address: [
        { required: true, message: '请输入联系地址', trigger: 'blur' }
      ]
    }

    // 标签页
    const activeTab = ref('basic')

    // 贷款记录
    const loanRecords = ref([])
    const loanLoading = ref(false)
    const loanPagination = reactive({
      currentPage: 1,
      pageSize: 5,
      total: 0
    })

    // 回访记录
    const visitRecords = ref([
      {
        visitTime: '2024-03-01 10:00:00',
        method: 'phone',
        content: '电话回访，客户反馈良好',
        feedback: 4,
        visitor: '张三',
        nextVisitTime: '2024-04-01 10:00:00'
      }
    ])

    // 服务记录
    const serviceRecords = ref([
      {
        type: 'consult',
        title: '贷款咨询',
        content: '咨询个人住房贷款相关事宜',
        status: 'completed',
        createTime: '2024-03-01 10:00:00',
        handler: '李四'
      }
    ])

    // 回访对话框
    const visitDialogVisible = ref(false)
    const visitFormRef = ref(null)
    const visitForm = reactive({
      method: '',
      content: '',
      feedback: 3,
      nextVisitTime: ''
    })

    const visitRules = {
      method: [
        { required: true, message: '请选择回访方式', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入回访内容', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
      ],
      feedback: [
        { required: true, message: '请选择客户反馈', trigger: 'change' }
      ],
      nextVisitTime: [
        { required: true, message: '请选择下次回访时间', trigger: 'change' }
      ]
    }

    // 服务对话框
    const serviceDialogVisible = ref(false)
    const serviceFormRef = ref(null)
    const serviceForm = reactive({
      type: '',
      title: '',
      content: ''
    })

    const serviceRules = {
      type: [
        { required: true, message: '请选择服务类型', trigger: 'change' }
      ],
      title: [
        { required: true, message: '请输入服务主题', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入服务内容', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
      ]
    }

    // 方法定义
    const goBack = () => {
      router.back()
    }

    const handleEdit = () => {
      isEdit.value = true
    }

    const handleSave = async () => {
      if (!basicFormRef.value) return
      
      try {
        await basicFormRef.value.validate()
        
        loading.value = true
        // 构建保存数据
        const saveData = { ...basicForm }
        
        // 调用API保存
        await customerApi.update(saveData)
        
        ElMessage.success('保存成功')
        isEdit.value = false
        fetchCustomerInfo() // 刷新数据
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        loading.value = false
      }
    }

    const cancelEdit = () => {
      isEdit.value = false
      fetchCustomerInfo() // 重置表单数据为服务器数据
    }

    const handleAddVisit = () => {
      visitForm.method = ''
      visitForm.content = ''
      visitForm.feedback = 3
      visitForm.nextVisitTime = ''
      visitDialogVisible.value = true
    }

    const submitVisit = async () => {
      if (!visitFormRef.value) return
      
      try {
        await visitFormRef.value.validate()
        // TODO: 实现提交逻辑
        ElMessage.success('回访记录添加成功')
        visitDialogVisible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }

    const handleAddService = () => {
      serviceForm.type = ''
      serviceForm.title = ''
      serviceForm.content = ''
      serviceDialogVisible.value = true
    }

    const submitService = async () => {
      if (!serviceFormRef.value) return
      
      try {
        await serviceFormRef.value.validate()
        // TODO: 实现提交逻辑
        ElMessage.success('服务记录添加成功')
        serviceDialogVisible.value = false
      } catch (error) {
        console.error('表单验证失败:', error)
      }
    }

    const formatMoney = (value) => {
      return `¥ ${value.toFixed(2)}`
    }

    const getLoanStatusType = (status) => {
      const map = {
        'pending': 'warning',
        'approved': 'success',
        'rejected': 'danger',
        'completed': 'info'
      }
      return map[status]
    }

    const getLoanStatusText = (status) => {
      const map = {
        'pending': '待审批',
        'approved': '已通过',
        'rejected': '已拒绝',
        'completed': '已结清'
      }
      return map[status]
    }

    const getVisitType = (method) => {
      const map = {
        'phone': 'primary',
        'visit': 'success',
        'email': 'warning'
      }
      return map[method]
    }

    const getVisitMethodText = (method) => {
      const map = {
        'phone': '电话',
        'visit': '上门',
        'email': '邮件'
      }
      return map[method]
    }

    const getServiceTypeText = (type) => {
      const map = {
        'consult': '咨询',
        'complaint': '投诉',
        'suggestion': '建议',
        'other': '其他'
      }
      return map[type]
    }

    const getServiceStatusType = (status) => {
      const map = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success'
      }
      return map[status]
    }

    const getServiceStatusText = (status) => {
      const map = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成'
      }
      return map[status]
    }

    // 初始化页面数据
    onMounted(async () => {
      if (customerId) {
        await fetchCustomerInfo()
        fetchCustomerLoanList()
        // 其他初始化操作...
      }
    })

    // 获取客户详情
    const fetchCustomerInfo = async () => {
      loading.value = true
      try {
        const res = await customerApi.getInfo(customerId)
        // 更新基本表单数据
        Object.keys(basicForm).forEach(key => {
          if (res.data[key] !== undefined) {
            basicForm[key] = res.data[key]
          }
        })
        
        // 如果有扩展信息，也进行更新
        if (res.data.extendInfo) {
          const extendInfo = res.data.extendInfo
          Object.keys(extendInfo).forEach(key => {
            if (basicForm[key] !== undefined) {
              basicForm[key] = extendInfo[key]
            }
          })
        }
      } catch (error) {
        console.error('获取客户信息失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 获取客户贷款记录
    const fetchCustomerLoanList = () => {
      loanLoading.value = true
      const params = {
        custId: customerId,
        pageNum: loanPagination.currentPage,
        pageSize: loanPagination.pageSize
      }
      
      customerApi.getLoanList(params).then(res => {
        loanRecords.value = res.data.rows
        loanPagination.total = res.data.total
      }).catch(error => {
        console.error('获取客户贷款记录失败:', error)
      }).finally(() => {
        loanLoading.value = false
      })
    }

    // 查看贷款详情
    const handleViewLoanDetail = (loanId) => {
      router.push(`/loan/detail/${loanId}`)
    }

    // 贷款分页处理
    const handleLoanCurrentChange = (val) => {
      loanPagination.currentPage = val
      fetchCustomerLoanList()
    }

    const handleLoanSizeChange = (val) => {
      loanPagination.pageSize = val
      loanPagination.currentPage = 1
      fetchCustomerLoanList()
    }

    return {
      customerId,
      basicFormRef,
      isEdit,
      basicForm,
      basicRules,
      activeTab,
      loanRecords,
      loanLoading,
      loanPagination,
      visitRecords,
      serviceRecords,
      visitDialogVisible,
      visitFormRef,
      visitForm,
      visitRules,
      serviceDialogVisible,
      serviceFormRef,
      serviceForm,
      serviceRules,
      goBack,
      handleEdit,
      handleSave,
      cancelEdit,
      handleAddVisit,
      submitVisit,
      handleAddService,
      submitService,
      formatMoney,
      getLoanStatusType,
      getLoanStatusText,
      getVisitType,
      getVisitMethodText,
      getServiceTypeText,
      getServiceStatusType,
      getServiceStatusText,
      fetchCustomerInfo,
      fetchCustomerLoanList,
      handleViewLoanDetail,
      handleLoanCurrentChange,
      handleLoanSizeChange
    }
  }
}
</script>

<style scoped>
.customer-detail {
  padding: 20px;
}

.page-header-content {
  font-size: 20px;
  font-weight: bold;
}

.detail-content {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #409EFF;
}

.form-card {
  margin-bottom: 20px;
}

.timeline-card {
  margin-bottom: 10px;
}

.visit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.visit-footer {
  margin-top: 10px;
  color: #666;
  display: flex;
  justify-content: space-between;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-timeline-item__node--primary) {
  background-color: #409EFF;
}

:deep(.el-timeline-item__node--success) {
  background-color: #67C23A;
}

:deep(.el-timeline-item__node--warning) {
  background-color: #E6A23C;
}
</style> 